#include "data/entry.h"
#include "database/connection.h"
#include "database/database.h"
#include "scanner/movie_processor.h"

namespace Tvimeg
{
	int MovieProcessor::AddEntry(const Entry& entry) const
	{
		// add the movie to the database
		Connection& connection = Database::GetInstance().GetConnection();
		connection.PrepareQuery("INSERT INTO movies (lookupTitle) VALUES (?1);");
		connection.BindText(1, entry.GetName());
		if (connection.ExecuteQuery())
		{
			return connection.GetLastId();
		}
		else
		{
			return -1;
		}
	}

	int MovieProcessor::UpdateEntry(const Entry& entry) const
	{
		// get the connection object
		Connection& connection = Database::GetInstance().GetConnection();

		// attempt to find one of the files so we can get the movie id
		int movieId = -1;
		const Entry::FilesIterator end = entry.GetFilesEnd();
		for (Entry::FilesIterator file = entry.GetFilesBegin(); movieId == -1 && file != end; ++file)
		{
			// try to find the file in the files table
			connection.PrepareQuery("SELECT id FROM files WHERE path = ?1;");
			connection.BindText(1, file->GetPath());
			if (connection.NextRow())
			{
				// found the file, now try to find the id of the movie related to this file
				const int fileId = connection.GetInt(0);
				connection.PrepareQuery("SELECT movieId FROM movieFiles WHERE fileId = ?1;");
				connection.BindInt(1, fileId);
				if (connection.NextRow())
				{
					// found the movie id
					movieId = connection.GetInt(0);
				}
			}
		}

		// did we find the movie
		if (movieId != -1)
		{
			// found the movie, so update the lookup title
			connection.PrepareQuery("UPDATE movies SET lookupTitle = ?1 WHERE id = ?2;");
			connection.BindText(1, entry.GetName());
			connection.BindInt(2, movieId);
			connection.ExecuteQuery();

			// return the movie id
			return movieId;
		}
		else
		{
			// didn't find the movie, so just add it
			return AddEntry(entry);
		}
	}

	void MovieProcessor::RemoveEntryFiles(const int entryId) const
	{
		Connection& connection = Database::GetInstance().GetConnection();
		connection.PrepareQuery("DELETE FROM movieFiles WHERE movieId = ?1;");
		connection.BindInt(1, entryId);
		connection.ExecuteQuery();
	}

	void MovieProcessor::AddEntryFile(const int fileId, const int entryId) const
	{
		// add the link between the a file and a movie
		Connection& connection = Database::GetInstance().GetConnection();
		connection.PrepareQuery("INSERT INTO movieFiles (movieId, fileId) VALUES (?1, ?2);");
		connection.BindInt(1, entryId);
		connection.BindInt(2, fileId);
		connection.ExecuteQuery();
	}
}
